package com.azdebugit.concurrent.lock;

public class TheBackLock {

    public static String object1 = "obj1";
    public static String object2 = "obj2";

    public static void main(String[] args) {
        Thread thread = new Thread(new MyThread(false));
        Thread thread1 = new Thread(new MyThread(true));
        thread.start();
        thread1.start();
    }

}

class MyThread implements Runnable {

    private boolean flag;

    public MyThread(boolean flag) {
        this.flag = flag;
    }

    @Override
    public void run() {
        if (flag) {
            try {
                while (true) {
                    synchronized (TheBackLock.object1) {
                        System.out.println(Thread.currentThread().getName() + "lock object1");
                        Thread.sleep(3000);
                        synchronized (TheBackLock.object2) {
                            System.out.println(Thread.currentThread().getName() + "lock object2");
                        }
                    }
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        } else {
            try {
                while (true) {
                    synchronized (TheBackLock.object2) {
                        System.out.println(Thread.currentThread().getName() + "lock object2");
                        Thread.sleep(3000);
                        synchronized (TheBackLock.object1) {
                            System.out.println(Thread.currentThread().getName() + "lock object1");
                        }
                    }
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

    }
}